package com.iwop.moto.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.comm.Page;
import com.iwop.moto.model.MStoreService;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.service.FOrderServiceService;
import com.iwop.moto.service.StoreService;
import com.iwop.moto.service.StoreServieService;
import com.iwop.moto.service.UserService;
import com.iwop.moto.utils.PushNoticeUtil;
import com.iwop.moto.utils.stringUtil.DateUtils;
import com.iwop.moto.utils.stringUtil.ObjectId;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/*************************************************
 * 店铺服务：
 * 流程
 * 1：用户推送我要服务给附件10个商家M_STORE_SERVICE_USER
 * 2：商家接收(抢单)
 * 3：商家服务
 * 4：商家推送付款
 * 5：用户付款
 * @author huyuangui on 2016/7/12.
 *************************************************/
@Controller
public class StoreServiceController extends BaseController {
    @Autowired
    private StoreServieService storeServieService;
    @Autowired
    private StoreService storeService;
    @Autowired
    FOrderServiceService fOrderServiceService;
    @Autowired
    UserService userService;
    /***********************************************************************
     * 我要服务
     * 服务ID
     * @param request
     *
     * 参数：address 地址
     *
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store/need/service")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel needService(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        SuperRecordModel superRecordModel=this.getSRModel();
      /*  if(StringUtils.isEmpty(superRecordModel.getString("serviceinfo"))){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NEED);
            return  resultModel;
        }*/
        String indexPage=superRecordModel.getString("indexPage");
        if(StringUtils.isEmpty(indexPage)){
            indexPage="1";
        }
        superRecordModel.put("status","1");
        superRecordModel.put("start_distance",0);
        superRecordModel.put("end_distance",6000);
        Page page=new Page(Integer.parseInt(indexPage),10);
        //获取最近的10家店 并保存
        page=storeService.selectByLatLog(superRecordModel, page);
        //page=storeServieService.findStoreByLatLog(superRecordModel, page);
        if(page==null || page.getCurRecordCount()<1){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NOSTORE);
            return resultModel;
        }
        superRecordModel.put("ser_user_id",superRecordModel.getString("session_id"));
        superRecordModel.put("sid",SequenceUtil.Serial("S"));
        superRecordModel.put("addtime",new Date());
        superRecordModel.put("status","0");
        storeServieService.saveStoreService(superRecordModel);
        //保存
        for (int i=0;i<page.getCurRecordCount();i++){
            SuperRecordModel temp=new SuperRecordModel();
            SuperRecordModel tempStore=(SuperRecordModel)page.getList().get(i);
            temp.put("sid",superRecordModel.getString("sid")+"_"+(i+1));
            temp.put("service_id",superRecordModel.getString("sid"));
            temp.put("to_storeid",tempStore.getString("sid"));
            temp.put("to_userid", superRecordModel.getString("session_id"));
            temp.put("distances", tempStore.get("juli"));
            temp.put("addtime", DateUtils.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
            temp.put("status","0");
            storeServieService.saveStoreServerUser(temp);
            PushNoticeUtil.sendPersonNotice("您有一笔服务订单等待抢单","store",tempStore.getString("user_id"));
        }
        return resultModel;
    }

    /**
     * 功能：列表
     * 店铺获取在线订单,已接订单
     * 参数：storeid 店铺id
     * 参数：status 状态0未处理订单1已处理
     * */
    @RequestMapping("/api/store/service/order/list")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel storeServicelist(HttpServletRequest request){
        List<SuperRecordModel> list = null;
        try {
            SuperRecordModel superRecordModel=this.getSRModel();
            list = storeServieService.findByServiceOderListStoreId(superRecordModel);
            return getSucceed(list,ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能：H5 在线订单列表
     * 店铺获取在线订单,已接订单
     * 参数：storeId 店铺id
     * 参数：status 状态0未处理订单1已处理
     * */
    @RequestMapping("/api/store/service/order/entry")
    @ResponseBody
    public ResultModel storeServiceH5list(HttpServletRequest request){
        List<SuperRecordModel> list = null;
        try {
            SuperRecordModel superRecordModel=this.getSRModel();
            String name = request.getParameter("name");
            if(StringUtils.isEmpty(name)){
                superRecordModel.put("name",null);
            }
            list = storeServieService.findByServiceOderH5StoreId(superRecordModel);
            return getSucceed(list,ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能：详情
     * 参数：service_id m_store_service主键
     * 参数：storeid 店铺id
     * 参数：status 0未处理 1处理中 2已处理
     * */
    @RequestMapping("/api/store/service/order/detail")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel storeServicedetail(HttpServletRequest request) {
        SuperRecordModel superRecordModel=this.getSRModel();
        SuperRecordModel superRecord = null;
        try {
            SuperRecordModel storeOrder = fOrderServiceService.getStoreOrderDetailByServiceId(superRecordModel);
            superRecord = storeServieService.findByServiceOderDetailStoreId(superRecordModel);
            if(superRecord==null){
                return getErr(ErrCode.ERROR_ORDER_SERVICE_NO_EXIST);
            }
            if (storeOrder!=null && (!StringUtils.isEmpty(storeOrder.getString("content")))){
                superRecord.put("isExistOrder","yes");
            }else {
                superRecord.put("isExistOrder","no");
            }
            ResultModel resultModel = new ResultModel();
            resultModel.setData(JSON.toJSONString(superRecord));
            return resultModel;
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 抢单
     * 参数：sid m_store_service
     * 参数：to_storeid 店铺id
     * */
    @RequestMapping("/api/store/service/order/detail/update")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel storeServiceUpdate(){
        SuperRecordModel superRecordModel=this.getSRModel();
        try {
            SuperRecordModel service=storeServieService.findServiceBySid(superRecordModel);
            if(service==null){
                return getErr(ErrCode.ERROR_ORDER_SERVICE_NO_EXIST);
            }else {
                SuperRecordModel srMpdel= fOrderServiceService.getStoreOrderBySid(service.getString("sid"));
                if(srMpdel==null){
                    superRecordModel.put("status","1");
                    storeServieService.updateStoreService(superRecordModel);
                    SuperRecordModel SRModel=new SuperRecordModel();
                    String user_id = service.getString("ser_user_id");
                    SRModel.put("service_id",service.getString("sid"));
                    SRModel.put("orderno",SequenceUtil.Serial("SO"));
                    SRModel.put("sid", ObjectId.userUUID());
                    SuperRecordModel srm=new SuperRecordModel();
                    srm.put("userId", user_id);
                    SuperRecordModel userBySid = userService.findUserBySid(srm);
                    if (userBySid!=null){
                        SRModel.put("user_name",userBySid.getString("nickname"));
                        SRModel.put("user_tel",userBySid.getString("tel"));
                    }
                    SRModel.put("user_id", user_id);
                    SRModel.put("store_id", superRecordModel.getString("to_storeid"));
                    SRModel.put("pushstatus","0");
                    SRModel.put("status_flag","1");
                    SRModel.put("order_type","store");
                    SRModel.put("status_time",new Date());
                    fOrderServiceService.insertStoreOrder(SRModel);
                    SuperRecordModel byId = storeService.getStoreBySid(superRecordModel.getString("to_storeid"));
                    PushNoticeUtil.sendPersonNotice(byId.getString("storename")+"已接收了您的订单","user",user_id);
                    return getSucceed(SRModel,ErrCode.SUCCEED);
                }else {
                    return getSucceed(ErrCode.SUCCEED);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 用户订单完成
     * 参数：storeid 店铺id
     * 参数：service_id 服务订单id
     * */
    @RequestMapping("/api/store/service/order/detail/finish")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel storeServiceFinish(){
        SuperRecordModel superRecordModel=this.getSRModel();
        List<SuperRecordModel> sModel=fOrderServiceService.getStoreOrderByService(superRecordModel.getString("service_id"));
        if(sModel==null || sModel.size()==0){
            return getErr(ErrCode.ERROR_SEVICE_ORDER);
        }
        superRecordModel.put("status","1");
        SuperRecordModel srm = storeServieService.findByServiceOderDetailStoreId(superRecordModel);
        if(srm==null){
            return getErr(ErrCode.ERROR_SYSTEM);
        }
        superRecordModel.put("to_storeid",superRecordModel.getString("storeid"));
        superRecordModel.put("status","2");
        superRecordModel.put("sid",superRecordModel.getString("service_id"));
        storeServieService.updateStoreService(superRecordModel);
        return getSucceed(ErrCode.SUCCEED);
    }

    /**
     * 保存用户去过的地址
     * */
    @RequestMapping("/user/add/map/history")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel serviceMapAdd(HttpServletRequest request){
        try {
            SuperRecordModel superRecordModel=this.getSRModel();
            superRecordModel.put("user_id",superRecordModel.getString("session_id"));
            superRecordModel.put("sid",ObjectId.UUID());
            superRecordModel.put("addtime",new Date());
            if(StringUtils.isEmpty(superRecordModel.getString("log"))||StringUtils.isEmpty(superRecordModel.getString("lat"))){
                return getErr(ErrCode.ERROR_PARAMETER);
            }
            storeServieService.addAreaHistory(superRecordModel);
            return getSucceed(ErrCode.SUCCEED);
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 显示用户去过的地址
     * */
    @RequestMapping("/user/map/history/list")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel serviceMapList(HttpServletRequest request){
        try {
            SuperRecordModel superRecordModel=this.getSRModel();
            superRecordModel.put("user_id",superRecordModel.getString("session_id"));
            List<SuperRecordModel> srm=storeServieService.areaHistoryList(superRecordModel);
            return getSucceed(srm,ErrCode.SUCCEED);
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 用户获取周围的维修店
     * */
    @RequestMapping("/user/store/list")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel getServiceStoreList(HttpServletRequest request){
        try {
            SuperRecordModel superRecordModel=this.getSRModel();
            List<SuperRecordModel> storeList = storeServieService.getStoreList(superRecordModel);
            return getSucceed(storeList,ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * user_id用户id status 0未接服务，1已经服务
     * */
    @RequestMapping("/api/store_order/popular/list")
    @ResponseBody
    public ResultModel getStoreOrderPopularList(){
      try {
          SuperRecordModel SRModel = this.getSRModel();
          List<SuperRecordModel> list=storeServieService.getStoreOrderPopularList(SRModel);
          return getSucceed(list,ErrCode.SUCCEED);
      }catch (Exception e){
          e.printStackTrace();
          return getErr(ErrCode.ERROR_SYSTEM);
      }
    }

    /**
     * sid 服务id
     * */
    @RequestMapping("/api/store_order/popular/delete")
    @ResponseBody
    public ResultModel deleteStoreOrderPopular(){
       try {
           SuperRecordModel SRModel = this.getSRModel();
           storeServieService.deleteStoreOrderPopular(SRModel);
           return getSucceed(ErrCode.SUCCEED);
       }catch (Exception e){
           e.printStackTrace();
           return getErr(ErrCode.ERROR_SYSTEM);
       }
    }






    /***********************************************************************
     * 店铺服务列表
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_servicelist")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel servicelist(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        String service_id=request.getParameter("service_id");
        String storeid=request.getParameter("storeid");
        String status=request.getParameter("status");
        String pageIndex=request.getParameter("pageIndex");
        if(StringUtils.isEmpty(pageIndex) || Integer.valueOf(pageIndex)<0){
            pageIndex="1";
        }
        if(StringUtils.isEmpty(storeid)){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return  resultModel;
        }
        if(StringUtils.isEmpty(service_id)){
            service_id="";
        }
        MStoreService mStoreService=new MStoreService();
        mStoreService.setStoreId(storeid);
        mStoreService.setStatus(status);
        mStoreService.setSid(service_id);
        Page page=new Page(Integer.valueOf(pageIndex),10);
        page=storeServieService.queryListByMStoreService(mStoreService, page);
        if(page==null ||  page.getCurRecordCount()<1){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_NOCOUNT);
            return  resultModel;
        }
        JSONObject json=new JSONObject();
        json.put("pageCount",page.getPageCount());
        json.put("list",page.getList());
        resultModel.setData(json.toJSONString());
        return resultModel;
    }


    /***********************************************************************
     * 获取服务详情及列表
     * 服务ID
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_findServiceInfo")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel findServiceInfo(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        String sid=request.getParameter("sid");
        if(StringUtils.isEmpty(sid)){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return  resultModel;
        }
        MStoreService mStoreService=new MStoreService();
        mStoreService.setSid(sid);
        mStoreService=storeServieService.findById(sid);
        Page page=new Page(1, Comm.MAX);
        page=storeServieService.queryListByMStoreService(mStoreService,page);
        if(page==null || page.getPageCount()<1){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_NOCOUNT);
            return  resultModel;
        }
        JSONObject json=new JSONObject();
        json.put("mStoreService",mStoreService);
        json.put("list",page.getList());
        resultModel.setData(json.toJSONString());
        return resultModel;
    }
    /***********************************************************************
     * 我要抢单
     * 服务ID
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_rushOrder")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel rushOrder(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        String sid=request.getParameter("sid");
        if(StringUtils.isEmpty(sid)){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return  resultModel;
        }
        MStoreService mStoreService=new MStoreService();
        mStoreService.setSid(sid);
        mStoreService=storeServieService.findById(sid);
        if(mStoreService==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NOEXIST);
            return resultModel;
        }
        //判断订单是否已被抢过
        if(mStoreService.getToUserId().length()>0) {
            if (mStoreService.getToUserId().equals(this.getUserId())) {
                return resultModel;
            }else{
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.STORE_ERROR_OTHERSERVED);
                return resultModel;
            }
        }
        //抢服务
        mStoreService=storeServieService.workService(mStoreService, this.getUserId(), "1");
        if (mStoreService.getToUserId().equals(this.getUserId())) {
            return resultModel;
        }else{
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_OTHERSERVED);
            return resultModel;
        }
//        return resultModel;
    }
    /***********************************************************************
     * 处理完成
     * 服务ID
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_workOverService")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel workOverService(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        String sid=request.getParameter("sid");
        if(StringUtils.isEmpty(sid)){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return  resultModel;
        }
        MStoreService mStoreService=new MStoreService();
        mStoreService.setSid(sid);
        mStoreService=storeServieService.findById(sid);
        if(mStoreService==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NOEXIST);
            return resultModel;
        }
        if(mStoreService.getToUserId().length()<1){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NORUSHOrder);
            return resultModel;
        }
        if (!mStoreService.getToUserId().equals(this.getUserId())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_OTHERSERVED);
            return resultModel;
        }
        //判断当前服务状态  服务状态不在处理中
        if(!mStoreService.getStatus().equals("1")){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NOWORKING);
            return resultModel;
        }
        //处理完成
        mStoreService=storeServieService.workService(mStoreService, this.getUserId(),"2");
        if (mStoreService!=null){
            return resultModel;
        }else{
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SAVE);
            return resultModel;
        }
//        return resultModel;
    }
    /***********************************************************************
     * 推送付款
     * 服务ID
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_pushPay")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel pushPay(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        SuperRecordModel superRecordModel=this.getSRModel();
        String sid=request.getParameter("sid");
        if(StringUtils.isEmpty(sid)){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return  resultModel;
        }
        MStoreService mStoreService=new MStoreService();
        mStoreService.setSid(sid);
        mStoreService=storeServieService.findById(sid);
        if(mStoreService==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NOEXIST);
            return resultModel;
        }
        if(mStoreService.getToUserId().length()<1){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NORUSHOrder);
            return resultModel;
        }
        if (!mStoreService.getToUserId().equals(this.getUserId())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_OTHERSERVED);
            return resultModel;
        }
        //判断当前服务状态  服务状态不在处理中
        if(!mStoreService.getStatus().equals("2")){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NOWORKOVER);
            return resultModel;
        }
        //处理完成 3推送付款
        mStoreService=storeServieService.workService(mStoreService, this.getUserId(),"3");
        if (mStoreService!=null){
            //项目  金额  图片  售后实现
            String servicename= superRecordModel.getString("servicename");
            String issuper= superRecordModel.getString("issuper");
            String aftersuper= superRecordModel.getString("aftersuper");
            String superstart= superRecordModel.getString("superstart");
            String superend= superRecordModel.getString("superend");
            String serviceImgs= superRecordModel.getString("serviceImgs");
            String rmoney= superRecordModel.getString("rmoney");
            if(StringUtils.isEmpty(servicename)){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.STORE_ERROR_SERVER_NAME_ISEMPTY);
                return resultModel;
            }
            if(StringUtils.isEmpty(rmoney))
            mStoreService.setServicename(servicename);
            mStoreService.setServiceimgs(serviceImgs);
            mStoreService.setIssuper(issuper);
            mStoreService.setSuperstart(StringUtils.isEmpty(superstart)?new Date():DateUtils.StringToDate(superstart));
            mStoreService.setSuperend(StringUtils.isEmpty(superend) ? new Date() : DateUtils.StringToDate(superend));
            mStoreService.setAftersuper(aftersuper);
            mStoreService.setRmoney(Long.valueOf(rmoney));
            mStoreService.setStatus("3");
            mStoreService=storeServieService.workService(mStoreService, this.getUserId(),"3");
            if (mStoreService!=null){
                return resultModel;
            }else{
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.STORE_ERROR_SAVE);
                return resultModel;
            }
        }else{
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_SAVE);
            return resultModel;
        }
    }

    // 待服务
    @RequestMapping("/api/service/nostore")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel getServiceForNo(HttpServletRequest request){
       try {
           SuperRecordModel superRecordModel=this.getSRModel();
           superRecordModel.put("user_id",superRecordModel.getString("session_id"));
           SuperRecordModel serviceNo = storeServieService.getServiceNo(superRecordModel);
           return getSucceed(serviceNo,ErrCode.SUCCEED);
       }catch (Exception e){
        return getErr(ErrCode.ERROR_SYSTEM);
       }
    }
}